﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data.Linq;
using System.Linq;
using System.Text;
using IntraVision.Web;
using IntraVision.Web.Filter;
using IntraVision.Web.Security;
using Model;

[AllowedRole("UserAdmin")]
public class UserPermissionController : EntityListController<User, NotarialServiceDataContext>
{
    protected override void EntityLoaded(NotarialServiceDataContext dc, User user)
    {
        ViewData["permissions"] = (from p in dc.Permissions orderby p.Id select p).ToList();
        ViewData["userpermissions"] = (from up in user.UserPermissions orderby up.Permission.PermissionGroup.Id select up.PermissionId).ToArray();
        ViewData["groups"] = (from g in dc.PermissionGroups orderby g.Id select g).ToList();
    }

    protected override void BeforeSubmit(NotarialServiceDataContext dc, User user)
    {
        #region Сохранить полномочия

        int[] ids = RequestHelper.GetIdsFromString(Request["pid"]);

        if (ids.Length == 0)
            dc.UserPermissions.DeleteAllOnSubmit(user.UserPermissions);
        else
        {
            dc.UserPermissions.DeleteAllOnSubmit((from p in user.UserPermissions where !ids.Contains(p.PermissionId) select p));
            int[] exids = (from up in user.UserPermissions select up.PermissionId).ToArray();
            foreach (int id in ids)
            {
                if (!exids.Contains(id))
                {
                    var up = new UserPermission();
                    up.PermissionId = id;
                    user.UserPermissions.Add(up);
                }
            }
        }
        
        #endregion
    }
}